// 数据库操作
const mongoose = require('mongoose');
// 对象规则验证
const Joi = require('joi');

const {
	Schema
} = mongoose;

// 定义后台菜单集合规则
const roleModel = new Schema({
	// 角色名称
	roleName: {
		type: String,
		minlength: 2,
		maxlength: 15,
		required: true
	},
	// 角色描述
	roleDesc: {
		type: String,
		minlength: 10,
		maxlength: 50,
		required: true
	},
	// 该角色所授权的权限
	children: [{
		_id: mongoose.Schema.Types.ObjectId,
		authName: { type: String },
		level: { type: Number },
		path: { type: String },
		icon: { type: String },
		children: [{
			_id: mongoose.Schema.Types.ObjectId,
			authName: { type: String },
			level: { type: Number },
			path: { type: String },
			icon: { type: String },
			children: [{
			_id: mongoose.Schema.Types.ObjectId,
			authName: { type: String },
			level: { type: Number },
			path: { type: String },
			icon: { type: String }
			}]
		}]
	}]
}, {
	versionKey: false
});

// authName: { type: String },
// 		level: { type: Number },
// 		path: { type: String },
// 		children: [{
// 			authName: { type: String },
// 			level: { type: Number },
// 			path: { type: String },
// 			children: [{
// 				authName: { type: String },
// 				level: { type: Number },
// 				path: { type: String },
// 			}]
// 		}]


// 用户集合类
const Role = mongoose.model('role', roleModel, 'role');

// 添加用户数据格式校验
const validateRole = role => {
	// 定义对象验证规则
	const schema = {
		roleName: Joi.string().min(2).max(15).required().error(new Error('角色名称字数应在2-15之间')),
		roleDesc: Joi.string().min(10).max(50).required().error(new Error('角色描述字数应在10-50之间'))

	};
	// 验证
	return Joi.validate(role, schema, {
		// 检测到所有错误
		abortEarly: false,
		// 允许对象包含被忽略的未知键
		allowUnknown: true
	});
}


// 导出对象
module.exports = {
	Role,
	validateRole
};
